<template>
  <div>
    <div class="row mb-1">
      <div class="col">
        <el-button @click="start" type="primary">查询</el-button>
        <el-button @click="dialogVisible = true" type="primary">添加</el-button>
        <!-- <el-button @click="addGropuLabel" type="primary">关联标签</el-button> -->
      </div>
    </div>
    <el-table
      class="margin-top20"
      :data="tableData"
      height="73vh"
      style="width: 100%"
      @sort-change="sortchange"
    >
      <el-table-column prop="ID" label="ID" width="80"></el-table-column>
      <el-table-column
        prop="name"
        label="名称"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="description"
        label="描述"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="vipauthoritylabel" label="关联标签">
        <template #default="{ row }">
          <el-tag
            class="question-intable-label"
            text
            type="primary"
            effect="plain"
            size="default"
            v-for="(v, key) in row.vipauthoritylabel"
            :key="`1-${key}`"
            >{{ v?.label?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdAt"
        sortable="custom"
        :formatter="({ createdAt }) => formatter(createdAt)"
        label="创建时间"
      ></el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button type="success" @click="addGroupLabel(row)" size="default"
            >标签</el-button
          >
          <el-button type="primary" @click="update(row)" size="default"
            >修改</el-button
          >
          <el-button type="danger" @click="del(row?.ID)" size="default"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pager"
      @current-change="handleCurrentChange"
      :page-size="Number(limit)"
      :page-sizes="pageSizes"
      @size-change="handleSizeChange"
      layout="total, sizes ,prev, pager, next"
      :total="totalCount"
    >
    </el-pagination>
    <!-- 添加 -->
    <el-dialog
      width="500px"
      title=""
      v-model="dialogVisible"
      :draggable="true"
      @closed="resetFrom"
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          {{ fromData.ID ? "修改" : "添加" }}
        </span>
      </template>
      <el-form
        ref="formRef"
        :model="fromData"
        label-width="auto"
        size="default"
      >
        <el-form-item
          label="分组名称"
          prop="name"
          :rules="[{ required: true, message: '请输入分组名称' }]"
        >
          <el-input
            v-model.trim="fromData.name"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="分组描述" prop="description">
          <el-input
            v-model.trim="fromData.description"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item> </el-form-item>
        <div class="text-right">
          <el-button type="primary" @click="submit(formRef)">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 关联标签 -->
    <el-drawer
      class="my-el-drawer"
      size="75%"
      append-to="#app"
      v-model="showGroupLabelDrawer"
      title="关联标签"
      @close="closeDrawer"
    >
      <template #header="{ close, titleId, titleClass }">
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          <span :id="titleId" :class="titleClass"
            >{{ selectedGroup?.name }}-标签列表</span
          >
        </span>
      </template>
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form
            class=""
            :inline="true"
            label-width="0"
            size="default"
            style="width: 100%"
          >
            <el-form-item>
              <el-button type="primary" size="default" @click="getAllLabel"
                >刷新标签</el-button
              >
            </el-form-item>
          </el-form>
          <el-table class="" :data="allLabel" height="73vh" style="width: 100%">
            <el-table-column prop="ID" label="ID" width="80"></el-table-column>
            <el-table-column
              prop="type"
              label="类型"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="name"
              label="名称"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="添加" width="80">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  :icon="Plus"
                  @click="updateGroupLabel(row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="12">
          <el-form
            class=""
            :inline="true"
            label-width="0"
            size="default"
            style="width: 100%"
          >
            <el-form-item>
              <el-button type="primary" size="default" @click="getAllGroupLabel"
                >刷新</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            class=""
            :data="allGroupLabel"
            height="73vh"
            style="width: 100%"
          >
            <el-table-column prop="ID" label="ID" width="80"></el-table-column>
            <el-table-column
              prop="vipauthority.name"
              label="分组名称"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="label.name"
              label="标签名称"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="删除" width="80">
              <template #default="{ row }">
                <el-button
                  type="danger"
                  :icon="Delete"
                  @click="delGroupLabel(row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { inject, onMounted, ref } from "vue";
import {
  asyncDelVipAuthority,
  asyncDelVipAuthorityLabel,
  asyncselectlabel,
  asyncSelectVipAuthority,
  asyncSelectVipAuthorityLabel,
  asyncUpdateVipAuthority,
  asyncUpdateVipAuthorityLabel,
} from "../../../api/index";
import { toLocaleDateString } from "../../../util/time";

import { useStore } from "vuex";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { vipType } from "./data";

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

const defaultVipGroup = {
  ID: undefined,
  name: "",
  description: "",
  tenant_id,
};
const store = useStore(Storekey);

const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200];
const offset = ref(0);
const _sortable = ref<"DESC" | "ASC">("DESC");
const _order = ref(["ID"]);
const tableData = ref<Studycodemodel.Ivipauthority[]>([]);
const totalCount = ref(0);

onMounted(() => {
  start();
});
async function start() {
  const { rows, count } = await asyncSelectVipAuthority({
    _limit: limit.value,
    _offset: offset.value,
    _sortable: _sortable.value || "DESC",
    _order: _order.value || ["ID"],
    tenant_id,
  });
  tableData.value = rows;
  totalCount.value = count;
}
function handleCurrentChange(val: number) {
  offset.value = limit.value * (val - 1);
  start();
}
const handleSizeChange = (val: number) => {
  limit.value = val;
  start();
};
// 排序
function sortchange(row: {
  column: any;
  prop: string;
  order: "ascending" | "descending" | null;
}) {
  const { prop, order } = row;
  if (order == "descending") {
    _sortable.value = "DESC";
  } else {
    _sortable.value = "ASC";
  }
  _order.value.push(prop);
  start();
}
function formatter(updatedAt: string) {
  return toLocaleDateString(updatedAt);
}

// 添加
const fromData = ref<Studycodemodel.Ivipauthority>({ ...defaultVipGroup });
const formRef = ref<FormInstance>();
const dialogVisible = ref(false);
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        await asyncUpdateVipAuthority({ ...fromData.value });
        ElMessage({ message: "操作成功", type: "success" });
        start();
        dialogVisible.value = false;
      } catch (e: any) {
        ElMessage({ message: e, type: "error" });
      }
    } else {
      console.log("error submit!");
    }
  });
};

const update = (row: Studycodemodel.Ivipauthority) => {
  dialogVisible.value = true;
  fromData.value = row;
};
// reset
const resetFrom = () => {
  fromData.value = { ...defaultVipGroup };
};

async function del(ID: number) {
  ElMessageBox.confirm("确定要删除此分组", "警告", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(async () => {
      try {
        await asyncDelVipAuthority({ ID });
        ElMessage({ message: "删除成功", type: "success" });
        store.dispatch("actionlabel");
        start();
      } catch (e) {
        ElMessage({ message: String(e), type: "error" });
      }
    })
    .catch(() => {
      ElMessage({ type: "info", message: "已取消" });
    });
}

// 关联标签弹窗
const selectedGroup = ref<Studycodemodel.Ivipauthority>({});
const showGroupLabelDrawer = ref(false);
function closeDrawer() {
  showGroupLabelDrawer.value = false;
  start();
}

const addGroupLabel = async (row: Studycodemodel.Ivipauthority) => {
  selectedGroup.value = row;
  showGroupLabelDrawer.value = true;
  getAllLabel();
  getAllGroupLabel();
};
//
const allGroupLabel = ref<Studycodemodel.Ivipauthoritylabel[]>([]);
const allGroupLabelCount = ref(0);
const allLabel = ref<Studycodemodel.ILabel[]>([]);
const allLabelCount = ref(0);
const getAllLabel = async () => {
  const { rows: labelList, count: labelCount } = await asyncselectlabel({
    _order: ["ID"],
    _sortable: "DESC",
    type: vipType,
  });
  allLabel.value = labelList;
  allLabelCount.value = labelCount;
};
const getAllGroupLabel = async () => {
  const { rows, count } = await asyncSelectVipAuthorityLabel({
    vipauthorityid: selectedGroup.value?.ID,
    _order: ["ID"],
    _sortable: "DESC",
  });
  allGroupLabel.value = rows;
  allGroupLabelCount.value = count;
};

// 添加标签
const updateGroupLabel = async (row: Studycodemodel.ILabel) => {
  try {
    // check
    const { count, rows } = await asyncSelectVipAuthorityLabel({
      vipauthorityid: selectedGroup.value?.ID,
      labelid: row?.ID,
    });
    if (count) {
      ElMessage({
        message: `标签：${row.name} 已存在，无需重复添加`,
        type: "warning",
      });
      return;
    }
    await asyncUpdateVipAuthorityLabel({
      labelid: row?.ID,
      vipauthorityid: selectedGroup.value?.ID,
    });
    ElMessage({ message: "操作成功", type: "success" });
    getAllGroupLabel();
  } catch (e) {
    ElMessage({ message: String(e), type: "error" });
  }
};
// 删除分组-标签
const delGroupLabel = async (row: Studycodemodel.Ivipauthoritylabel) => {
  ElMessageBox.confirm("确定要删除此标签", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await asyncDelVipAuthorityLabel({ ID: row?.ID! });
        ElMessage({ message: "操作成功", type: "success" });
        getAllGroupLabel();
      } catch (e) {
        ElMessage({ message: String(e), type: "error" });
      }
    })
    .catch(() => {
      ElMessage({ type: "info", message: "已取消" });
    });
};
</script>
